package com.uinnova.product.eam.service.dix.api.impl;

import com.binary.core.util.BinaryUtils;
import com.uinnova.product.eam.comm.model.es.AppSystemSyncRecord;
import com.uinnova.product.eam.service.dix.api.AppSystemSyncRecordSvc;
import com.uinnova.product.eam.service.es.AppSystemSyncRecordDao;
import com.uino.dao.util.ESUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 应用系统对接记录(新网-DDM)
 * @author ch
 */
@Service
public class AppSystemSyncRecordSvcImpl implements AppSystemSyncRecordSvc {
    @Autowired
    private AppSystemSyncRecordDao syncRecordDao;

    @Override
    public Long saveOrUpdate(AppSystemSyncRecord record){
        if(record.getId() == null){
            record.setId(ESUtil.getUUID());
        }
        return syncRecordDao.saveOrUpdate(record);
    }

    @Override
    public AppSystemSyncRecord getMaxVersionRecordBySystemId(String systemId) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.termQuery("systemId.keyword", systemId));
        Map<String, BigDecimal> versionMap = syncRecordDao.groupByFieldMaxVal("systemId.keyword", "version", boolQuery);
        if(BinaryUtils.isEmpty(versionMap) || versionMap.get(systemId) == null){
            return null;
        }
        int maxVersion = versionMap.get(systemId).intValue();
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.must(QueryBuilders.termQuery("systemId.keyword", systemId));
        query.must(QueryBuilders.termQuery("version", maxVersion));
        return syncRecordDao.selectOne(query);
    }

}
